#include "human_detect.h"
#include <stdio.h>
#include "los_task.h"
#include "iot_gpio.h"
#include "iot_errno.h"

/* GPIO定义 */
#define GPIO_BODY_INDUCTION GPIO0_PA3

/* 全局变量 */
volatile uint8_t g_human_detected = 0;
volatile uint8_t g_no_detection_count = 0;

/* 中断处理函数 */
static void gpio_isr_func(void *args)
{
    printf("Human detected!\n");
    g_human_detected = 1;
    g_no_detection_count = 0;
}

void human_check_task(void *arg)
{
    /* 初始化GPIO */
    (void)IoTGpioInit(GPIO_BODY_INDUCTION);
    (void)IoTGpioSetDir(GPIO_BODY_INDUCTION, IOT_GPIO_DIR_IN);
    
    /* 设置中断 */
    int ret = IoTGpioRegisterIsrFunc(GPIO_BODY_INDUCTION, 
                    IOT_INT_TYPE_EDGE, 
                    IOT_GPIO_EDGE_RISE_LEVEL_HIGH, 
                    gpio_isr_func, NULL);
    if (ret != IOT_SUCCESS) {
        printf("Failed to register ISR: %d\n", ret);
        return;
    }
    (void)IoTGpioSetIsrMask(GPIO_BODY_INDUCTION, FALSE);
    
    while (1) {
        if (g_human_detected) {
            g_no_detection_count++;
            if (g_no_detection_count >= 10) {
                g_human_detected = 0;
                printf("No human detected for 10s\n");
            }
        }
        (void)LOS_Msleep(1000);
    }
}
